#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class CheckInForm : Form, IPassengerParentForm
    {
        CheckIn m_checkIn;
        SeaPortService m_SeaPortService;
        CheckInService m_bookingService;
        PassportService m_passportService;
        TravelAgentService m_TravelAgentService;
        ReportRequestService m_reportRequest;
        User m_current_user;
        EditMode m_editmode;
        CheckInService m_chekInService;
        MainForm m_mainForm;
        TripService m_tripService;
        VesselService m_vesselService;
        //int passengerCount = 0;
        UserControlManageCheckIn m_parentForm;
        ConfigurationService m_ConfigurationService;
        int m_available = 0;

        public CheckInForm(string name, CheckIn checkIn, User currentUser, MainForm mainForm, UserControlManageCheckIn parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_checkIn = checkIn;
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            m_SeaPortService = (SeaPortService)ServiceFactory.Instance().GetService(ServiceFactory.SEAPORT_SERVICE);
            m_tripService = (TripService)ServiceFactory.Instance().GetService(ServiceFactory.TRIP_SERVICE);
            m_chekInService = (CheckInService)ServiceFactory.Instance().GetService(ServiceFactory.BOOKING_SERVICE);
            m_bookingService = (CheckInService)ServiceFactory.Instance().GetService(ServiceFactory.BOOKING_SERVICE);
            m_TravelAgentService = (TravelAgentService)ServiceFactory.Instance().GetService(ServiceFactory.TRAVEL_AGENT_SERVICE);
            m_passportService = (PassportService)ServiceFactory.Instance().GetService(ServiceFactory.PASSPORT_SERVICE);
            m_vesselService = (VesselService)ServiceFactory.Instance().GetService(ServiceFactory.VESSEL_SERVICE);
            m_ConfigurationService = (ConfigurationService)ServiceFactory.Instance().GetService(ServiceFactory.CONFIGURATION_SERVICE);
            m_reportRequest = new ReportRequestService();
            initTimeAvailable();
            initButtonEvent();
            initComboDataSource();
            
            if (checkIn.m_bookingID == 0)
            {
                clearForm();
            }
            else
            {
                m_checkIn = m_bookingService.GetCheckInByID(checkIn.m_bookingID, m_current_user.TravelAgent);
                loadBooking();
                enableForm(editmode == EditMode.Edit && m_checkIn.m_bookingStatus == CheckInStatus.CheckIn);
            }
            setEditMode(editmode);
                        UpdatePassengerList();
            //enableForm(false);
            
            UpdatePassengerStatus();
            toolBarButtonSave.Visible = false;
        }

        private void initTimeAvailable()
        {
            timerUpdateBalance.Interval = 10000;
            timerUpdateBalance.Tick += new EventHandler(timerUpdateBalance_Tick);
            timerUpdateBalance.Start();

            timerAvailableReminder.Interval = 500;
            timerAvailableReminder.Tick += new EventHandler(timerAvailableReminder_Tick);
        }

        void timerAvailableReminder_Tick(object sender, EventArgs e)
        {
            labelavailable.Visible = !labelavailable.Visible;
        }

        void timerUpdateBalance_Tick(object sender, EventArgs e)
        {
            UpdatePassengerStatus();
            UpdatePassengerList();
        }

        private void UpdatePassengerStatus()
        {
            int capacity = m_checkIn.m_trip.m_vessel.m_capacity;
            int checkIn = m_bookingService.GetPassengerCountByStatusAndTrip(PassengerStatus.CheckIn, m_checkIn.m_trip);
            int boarded = m_bookingService.GetPassengerCountByStatusAndTrip(PassengerStatus.Boarding, m_checkIn.m_trip);
            int unboarded = m_bookingService.GetPassengerCountByStatusAndTrip(PassengerStatus.UnBoarded, m_checkIn.m_trip);
            int available = capacity - (checkIn + boarded + unboarded);
            m_available = available;

            labelCapacity.Text = capacity.ToString();
            labelCheckin.Text = checkIn.ToString();
            labelBoarded.Text = boarded.ToString();
            labelUnboarded.Text = unboarded.ToString();
            labelavailable.Text = available.ToString();

            if (available < 5)
            {
                labelavailable.ForeColor = Color.Red;
                timerAvailableReminder.Start();
            }
            else
            {
                labelavailable.ForeColor = Color.Black;
                timerAvailableReminder.Stop();
            }
        }

        private void UpdatePassengerList()
        {
            //Passenger selectedP = listViewPassenger.SelectedItem == null ? null : (Passenger)listViewPassenger.SelectedItem.Tag;
            IList selectedItems = new ArrayList();
            foreach (ListViewItem p in listViewPassenger.SelectedItems)
            {
                selectedItems.Add(p.Tag);
            }
            listViewPassenger.Items.Clear();
            m_checkIn.m_passengerList = m_bookingService.GetPassengerByBookingIDAndTravelAgent(m_checkIn, m_current_user.TravelAgent);
            foreach (Passenger p in m_checkIn.m_passengerList)
            {
                p.m_passport = m_passportService.GetPassportByID(p.m_passport.m_passportID);
                ListViewItem item = listViewPassenger.Items.Add(p.m_boardingPassCode);
                //item.ForeColor = isSamePassenger(p) ? Color.Black : Color.Red;
                item.SubItems.Add(p.m_passport.m_passportNo);
                item.SubItems.Add(p.m_passport.m_name);
                item.SubItems.Add(p.m_passport.m_gender);
                item.SubItems.Add(p.m_passport.m_birthDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_passport.m_nationality);
                item.SubItems.Add(p.m_passport.m_issueDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_passport.m_expireDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_ticketNo);
                item.SubItems.Add(p.m_passengerStatus.ToString());
                item.SubItems.Add(p.m_remark);
                item.Tag = p;
                //if (selectedP != null)
                //{
                //    item.Selected = selectedP.m_passangerID == p.m_passangerID;
                //}
                foreach (Passenger psg in selectedItems)
                {
                    if (!item.Selected)
                        item.Selected = psg.m_passangerID == p.m_passangerID;
                }
            }
            //passengerCount = m_bookingService.GetLatestBoardingPassNumber(m_checkIn.m_trip);
            calculateBook();
        }

        //void timerUpdateBalance_Tick(object sender, EventArgs e)
        //{
        //    TravelAgent travelagent = (TravelAgent)comboBoxTravelAgent.SelectedValue;
        //    decimal availableOneWay = m_bookingService.GetAvailableBook(travelagent.TravelAgentID, TicketType.OneWay);
        //    decimal availableTwoWay = m_bookingService.GetAvailableBook(travelagent.TravelAgentID, TicketType.TwoWay);
        //     labelAvTicketOneWay.Text = availableOneWay.ToString();
        //     labelAvTicketTwoWay.Text = availableTwoWay.ToString();
        //    if (m_booking.m_bookingID == 0)
        //    {
        //        //labelAvTicketOneWay.Text = availableOneWay.ToString();
        //        //labelAvTicketTwoWay.Text = availableTwoWay.ToString();
        //        //labelBalance.Text = (available - numericUpDownBooked.Value).ToString();
        //    }
        //    else
        //    {
        //        //labelAvTicketTwoWay.Text = (availableTwoWay + m_booking.m_bookNumber).ToString();
        //       // labelAvTicketOneWay.Text = (availableOneWay + m_booking.m_bookNumber).ToString();
        //        //labelBalance.Text = ((available + m_booking.m_bookNumber) - numericUpDownBooked.Value).ToString();
        //    }
        //}
        private void clearForm()
        {
            //textBoxName.Text = string.Empty;
           // textBoxUserCode.Text = "AUTONUMBER";
           // numericUpDownBooked.Value = 1;
            comboBoxDepartureSeaPort.SelectedIndex = -1;
            //comboBoxReturnSeaPort.SelectedIndex = comboBoxReturnSeaPort.Items.Count > 2 ? 2 : -1;
            dateTimePickerDepartureDate.Value = DateTime.Today;
           // comboBoxTicketType.Text = TicketType.TwoWay.ToString();
            listViewPassenger.Items.Clear();
            textBoxRemark.Text = "";
           // dateTimePickerBookDate.Value = DateTime.Today;
            //dateTimePickerReturnDate.Value = DateTime.Today;
            m_checkIn = new CheckIn();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
           // textBoxName.SelectAll();
            comboBoxTravelAgent.Text = m_current_user.TravelAgent.Name;
            comboBoxDepartureTime.DataSource = null;
            comboBoxDepartureTrip.DataSource = null;
            //passengerCount = 0;
            // comboBoxReturnTrip.DataSource = null;
            // comboBoxReturnTime.DataSource = null;
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }

        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            //setEditMode(EditMode.Edit);
            //enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
                MessageBox.Show("Are you sure to exit?", "Exit Confirmation", MessageBoxButtons.YesNo,
                   MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
            MessageBoxWindow msg = (MessageBoxWindow)sender;
            if (msg.DialogResult == DialogResult.Yes)
            {
                this.Close();
            }
        }
        private void initComboDataSource()
        {
            comboBoxDepartureSeaPort.DataSource = m_current_user.UserType == UserType.Administrators ? m_SeaPortService.LoadAllSeaPort() : m_SeaPortService.LoadAllActiveSeaPort();
            //comboBoxReturnSeaPort.DataSource = m_current_user.UserType == UserType.Administrators ? m_SeaPortService.LoadAllSeaPort() : m_SeaPortService.LoadAllSeaPort();
           // comboBoxTicketType.DataSource = Enum.GetValues(typeof(TicketType));
            comboBoxTravelAgent.DataSource = m_TravelAgentService.LoadAllTravelAgent();
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadBooking();
        }

        private void clearErrorProvider()
        {
           // errorProviderUser.SetError(textBoxUserCode, "");
           // errorProviderUser.SetError(textBoxName, "");
           // errorProviderUser.SetError(numericUpDownBooked, "");
            errorProviderUser.SetError(comboBoxDepartureSeaPort, "");
            errorProviderUser.SetError(comboBoxDepartureTrip, "");
            errorProviderUser.SetError(comboBoxTravelAgent, "");
        }
        private bool isValidForm()
        {
            clearErrorProvider();
           // bool valid_a = textBoxUserCode.Text != string.Empty;
            //decimal available = 0;
            //TicketType tt = (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
            //available = m_bookingService.GetAvailableBook(m_current_user.TravelAgent.TravelAgentID, tt);
            //bool valid_b = textBoxName.Text != string.Empty;
           // bool valid_c = numericUpDownBooked.Value != 0;
            bool valid_d = comboBoxDepartureSeaPort.SelectedValue != null;
            bool valid_e = comboBoxDepartureTrip.SelectedValue != null;
            //bool valid_h = comboBoxReturnTrip.SelectedValue != null;
            bool valid_g = comboBoxTravelAgent.SelectedValue != null;
            bool valid_f = listViewPassenger.Items.Count > 0;
           //  if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "Code can not be empty");
           // if (!valid_b) errorProviderUser.SetError(textBoxName, "Group can not be empty");
          //  if (!valid_c) errorProviderUser.SetError(numericUpDownBooked, "Book number can not be empty");
            if (!valid_d) errorProviderUser.SetError(comboBoxDepartureSeaPort, "SeaPort not be empty");
            if (!valid_e) errorProviderUser.SetError(comboBoxDepartureTrip, "Trip can not be empty");
          //   if (!valid_f) errorProviderUser.SetError(numericUpDownBooked, "Fill Passenger Please.");
            if (!valid_g) errorProviderUser.SetError(comboBoxTravelAgent, "Travel agent cannot empty");
            //if (!valid_h) errorProviderUser.SetError(comboBoxReturnTrip, "Return Trip cannot empty");
            return valid_d && valid_e && valid_g && valid_f;//&& valid_h;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_checkIn.m_bookingCode = m_checkIn.m_bookingID > 0 ? m_checkIn.m_bookingCode : "autonumber";
                    m_checkIn.m_groupName = "";//textBoxName.Text;
                    m_checkIn.m_bookingDate = DateTime.Today;//dateTimePickerBookDate.Value;
                    m_checkIn.m_trip = (Trip)comboBoxDepartureTrip.SelectedValue;
                    m_checkIn.m_travelAgent = (TravelAgent)comboBoxTravelAgent.SelectedValue;
                    m_checkIn.m_bookNumber = 0;// numericUpDownBooked.Value;
                    m_checkIn.m_remark = textBoxRemark.Text;
                    m_checkIn.m_ticketType = TicketType.TwoWay;// (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
                    m_checkIn.m_departureDate = m_checkIn.m_trip.m_departureTime;// dateTimePickerDepartureDate.Value;//.AddHours(dateTimePickerDepTime.Value.Hour).AddMinutes(dateTimePickerDepTime.Value.Minute);
                    //  m_booking.m_returntrip = (Trip)comboBoxReturnTrip.SelectedValue;
                    //  m_booking.m_returnDate = m_booking.m_returntrip.m_departureTime;//dateTimePickerReturn.Value.AddHours(dateTimePickerReturnTime.Value.Hour).AddMinutes(dateTimePickerReturnTime.Value.Minute);
                    loadPassenger();
                    if (m_checkIn.m_passengerList.Count < m_checkIn.m_bookNumber)
                        m_checkIn.m_bookNumber = m_checkIn.m_passengerList.Count;
                    if (m_checkIn.m_bookingID > 0)
                    {
                        m_checkIn.m_modfctnBy = m_current_user.UserID;
                        m_chekInService.UpdateCheckIn(m_checkIn, m_current_user.TravelAgent);
                    }
                    else
                    {
                        m_checkIn.m_cretnBy = m_current_user.UserID;
                        m_chekInService.InserCheckIn(m_checkIn);
                    }
                    m_parentForm.LoadAllBooking();
                    //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved [" + m_checkIn.m_bookingCode + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                    //this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        private void loadPassenger()
        {
            m_checkIn.m_passengerList.Clear();
            foreach (ListViewItem itm in listViewPassenger.Items)
            {
                Passenger p = (Passenger)itm.Tag;
                if (p == null) continue;
                m_checkIn.m_passengerList.Add(p);
            }
        }

        void closeForm(object sender, EventArgs e)
        {
            //reload after saved
            m_checkIn = m_bookingService.GetCheckInByID(m_checkIn.m_bookingID, m_current_user.TravelAgent);
            loadBooking();
            enableForm(false);
            //this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarMenu.Visible = !(editMode == EditMode.Load);
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete) && m_current_user.RoleDetails(this.Name).NewFlag && (m_checkIn.m_bookingStatus == CheckInStatus.CheckIn);
            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.RoleDetails(this.Name).UpdateFlag && (m_checkIn.m_bookingStatus == CheckInStatus.CheckIn);
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
           // textBoxName.ReadOnly = !enable;
          //  textBoxUserCode.ReadOnly = !enable;
           // numericUpDownBooked.Enabled = enable;
            comboBoxDepartureSeaPort.Enabled = false;// enable;
            //comboBoxReturnSeaPort.Enabled = false;
            dateTimePickerDepartureDate.Enabled = false;//enable;
            comboBoxDepartureTrip.Enabled = false;//false;
            //comboBoxReturnTrip.Enabled = false;
            //listViewPassenger.Enabled = enable;
            textBoxRemark.ReadOnly = true;//!enable;
            buttonREmove.Enabled = enable && listViewPassenger.SelectedItem != null;
            buttonViewPassenger.Enabled = enable && listViewPassenger.SelectedItem != null;
            buttonPrintItiPassenger.Enabled = listViewPassenger.SelectedItem != null && m_checkIn.m_bookingID > 0;
            buttonBoardingPass.Enabled = listViewPassenger.SelectedItem != null && m_checkIn.m_bookingID > 0;
            buttonBoardingPass2Way.Enabled = buttonBoardingPass.Enabled;
            buttonWildCard.Enabled = listViewPassenger.SelectedItem != null && m_checkIn.m_bookingID > 0;
            buttonKIMS.Enabled = listViewPassenger.SelectedItem != null && m_checkIn.m_bookingID > 0;
            buttonAddPassenger.Enabled = enable;
           // comboBoxTicketType.Enabled = false;
           // dateTimePickerBookDate.Enabled = enable;
            //dateTimePickerReturnDate.Enabled = enable;
            //dateTimePickerDepTime.Enabled = enable;
            comboBoxTravelAgent.Enabled = false;//enable && (m_current_user.UserType == UserType.Administrators);
            comboBoxDepartureTime.Enabled = false;//enable;
            //comboBoxReturnTime.Enabled = enable;
        }

        private void loadBooking()
        {
            m_checkIn.m_trip = m_tripService.GetTripByID(m_checkIn.m_trip.m_tripID);
            m_checkIn.m_trip.m_vessel = m_vesselService.GetVesselByID(m_checkIn.m_trip.m_vessel.m_vesselID);
            // m_booking.m_returntrip = m_tripService.GetTripByID(m_booking.m_returntrip.m_tripID);
            m_checkIn.m_trip.m_seaPort = m_SeaPortService.GetSeaPortByID(m_checkIn.m_trip.m_seaPort.m_seaPortID);
            // m_booking.m_returntrip.m_seaPort = m_SeaPortService.GetSeaPortByID(m_booking.m_returntrip.m_seaPort.m_seaPortID);
           // m_checkIn.m_travelAgent = m_TravelAgentService.GetTravelAgentByID(m_checkIn.m_travelAgent.TravelAgentID);

           // textBoxName.Text = m_checkIn.m_groupName;
          //  textBoxUserCode.Text = m_checkIn.m_bookingCode;
          //  numericUpDownBooked.Value = m_checkIn.m_bookNumber;

            comboBoxDepartureTrip.Text = m_checkIn.m_trip.ToString();
            comboBoxDepartureSeaPort.Text = m_checkIn.m_trip.m_seaPort.ToString();
            dateTimePickerDepartureDate.Value = m_checkIn.m_trip.m_departureDate;
            comboBoxDepartureTime.Text = m_checkIn.m_trip.m_departureTime.ToString("HH:mm");

            //comboBoxReturnTrip.Text = m_booking.m_returntrip.ToString();
            //comboBoxReturnSeaPort.Text = m_booking.m_returntrip.m_seaPort.ToString();
            //dateTimePickerReturnDate.Value = m_booking.m_returntrip.m_departureDate;
            //comboBoxReturnTime.Text = m_booking.m_returntrip.m_departureTime.ToString("HH:mm");

            textBoxRemark.Text = m_checkIn.m_remark;
           // comboBoxTicketType.Text = m_checkIn.m_ticketType.ToString();
           // dateTimePickerBookDate.Value = m_checkIn.m_bookingDate;
            comboBoxTravelAgent.Text = m_current_user.TravelAgent.ToString(); //m_checkIn.m_travelAgent.Name;
            textBoxVessel.Text = m_checkIn.m_trip.m_vessel.m_vesselName;
            
            //dateTimePickerDepTime.Value = m_booking.m_departureDate;

            listViewPassenger.Items.Clear();

            foreach (Passenger p in m_checkIn.m_passengerList)
            {
                p.m_passport = m_passportService.GetPassportByID(p.m_passport.m_passportID);
                ListViewItem item = listViewPassenger.Items.Add(p.m_boardingPassCode);
                //item.ForeColor = isSamePassenger(p) ? Color.Black : Color.Red;
                item.SubItems.Add(p.m_passport.m_passportNo);
                item.SubItems.Add(p.m_passport.m_name);
                item.SubItems.Add(p.m_passport.m_gender);
                item.SubItems.Add(p.m_passport.m_birthDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_passport.m_nationality);
                item.SubItems.Add(p.m_passport.m_issueDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_passport.m_expireDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_ticketNo);
                item.SubItems.Add(p.m_passengerStatus.ToString());
                item.Tag = p;

            }
            //passengerCount = m_bookingService.GetLatestBoardingPassNumber(m_checkIn.m_trip);
            //calculateBook();
        }

        private bool isSamePassenger(Passenger m_passenger)
        {
            bool sameTicket = true;
            if (m_passenger.m_passengerStatus == PassengerStatus.ReCheckIn)
            {
                m_passenger.PassangerHistory = m_bookingService.GetPassengerHistoryByPassengerID(m_passenger.m_passangerID);
                if (m_passenger.PassangerHistory != null)
                    sameTicket = m_passenger.PassangerHistory.m_ticketNo == m_passenger.m_ticketNo;
            }
            return
            sameTicket &&
            m_passenger.m_passport.m_issueDate == m_passenger.m_issueDate &&
            m_passenger.m_passport.m_expireDate == m_passenger.m_expireDate &&
            m_passenger.m_passport.m_country == m_passenger.m_country &&
            m_passenger.m_passport.m_officeIssue == m_passenger.m_officeIssue &&
            m_passenger.m_passport.m_passportNo == m_passenger.m_passportNo &&
            m_passenger.m_passport.m_name == m_passenger.m_name &&
            m_passenger.m_passport.m_gender.ToString() == m_passenger.m_gender.ToString() &&
            m_passenger.m_passport.m_birthPlace == m_passenger.m_birthPlace &&
            m_passenger.m_passport.m_birthDate == m_passenger.m_birthDate &&
            m_passenger.m_passport.m_nationality == m_passenger.m_nationality &&
            m_passenger.m_passport.m_placeOfResidence == m_passenger.m_placeOfResidence &&
            m_passenger.m_passport.m_occupation == m_passenger.m_occupation &&
            m_passenger.m_passport.m_maritalStatus.ToString() == m_passenger.m_maritalStatus.ToString() &&
            m_passenger.m_passport.m_address == m_passenger.m_address &&
            m_passenger.m_passport.m_city == m_passenger.m_city &&
            m_passenger.m_passport.m_zipcode == m_passenger.m_zipcode &&
            m_passenger.m_passport.m_remark == m_passenger.m_remark &&
            m_passenger.m_passport.m_idnumber == m_passenger.m_idnumber;
        }

        private void dateTimePickerDate_ValueChanged(object sender, EventArgs e)
        {
            comboBoxDepartureTrip.DataSource = null;
            if (comboBoxDepartureSeaPort.SelectedValue == null) return;
            SeaPort port = (SeaPort)comboBoxDepartureSeaPort.SelectedValue;
            comboBoxDepartureTrip.DataSource = m_tripService.LoadAllTripByDateAndSeaPort(dateTimePickerDepartureDate.Value, port.m_seaPortID);
            IList datasource = m_tripService.LoadAllTripByDateAndSeaPort(dateTimePickerDepartureDate.Value, port.m_seaPortID);
            comboBoxDepartureTime.DataSource = GetTimeList(datasource);
        }

        private IList GetTimeList(IList datasource)
        {
            IList result = new ArrayList();
            foreach (Trip trip in datasource)
            {
                result.Add(new TripTime(trip));
            }
            return result;
        }

        private void buttonAddPassenger_Click(object sender, EventArgs e)
        {
            if (comboBoxDepartureTrip.SelectedValue == null)
            {
                MessageBox.Show("Please select Trip", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }
            UpdatePassengerStatus();
            if (m_available == 0)
            {
                MessageBox.Show("There is no available seat for this Trip.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }
            listViewPassenger.SelectedItems.Clear();
            PassengerForm frm = new PassengerForm(this.Name, new Passenger(), new Passport(), m_current_user, m_mainForm, this, EditMode.Create);
            frm.ShowDialog();
        }

        public bool isAlreadyExist(Passenger p)
        {
            bool exist = false;
            foreach (ListViewItem itm in listViewPassenger.Items)
            {
                Passenger px = (Passenger)itm.Tag;
                if (px.m_passport.m_passportNo == p.m_passport.m_passportNo)
                {
                    exist = true;
                    break;
                }
            }
            Trip trip = (Trip)comboBoxDepartureTrip.SelectedValue;
            IList t = m_bookingService.GetBookingByPassengerPassport(p.m_passport.m_passportNo, trip);
            bool checkin = t.Count > 0;
            return exist || checkin;
        }

        public void UpdatePassenger(Passenger p)
        {
            p.m_remark = m_current_user.UserCode;
            m_chekInService.UpdatePassanger(p, m_current_user.TravelAgent);
            foreach (ListViewItem itm in listViewPassenger.Items)
            {
                Passenger px = (Passenger)itm.Tag;
                if (px.m_passangerID == p.m_passangerID)
                {
                    itm.SubItems[1].Text = p.m_passport.m_passportNo;
                    itm.SubItems[2].Text = p.m_passport.m_name;
                    itm.SubItems[3].Text = p.m_passport.m_gender;
                    itm.SubItems[4].Text = p.m_passport.m_birthDate.ToString("dd-MMM-yyyy");
                    itm.SubItems[5].Text = p.m_passport.m_nationality;
                    itm.SubItems[6].Text = p.m_passport.m_issueDate.ToString("dd-MMM-yyyy");
                    itm.SubItems[6].Text = p.m_passport.m_expireDate.ToString("dd-MMM-yyyy");
                    itm.SubItems[7].Text = p.m_ticketNo;
                    itm.SubItems[8].Text = p.m_passengerStatus.ToString();
                    break;
                }
            }
        }
        private string generateTicket(string ticket, string boardingpass)
        {
            if (ticket.Trim() != string.Empty)
                return ticket;
            Configuration conf = m_ConfigurationService.GetConfigurationByName("ticket_prefix");
            string tckt = conf.value_1 + boardingpass;
            return tckt;
        }
        public void AddPassenger(Passenger p)
        {

            //foreach (ListViewItem itm in listViewPassenger.Items)
            //{
            //    Passenger pss = (Passenger)itm.Tag;
            //    if (pss == null) continue;
            //    if (pss.m_passport.m_passportNo == p.m_passport.m_passportNo)
            //    {
            //        MessageBox.Show("Passport has already been add : " + p.m_passport.m_passportNo, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        return;
            //    }
            //}
             
            if (p.m_passport.m_passportID > 0)
            {
                if (p.m_passangerID == 0)
                {
                    foreach (ListViewItem itm in listViewPassenger.Items)
                    {
                        Passenger px = (Passenger)itm.Tag;
                        if (px.m_passport.m_passportNo == p.m_passport.m_passportNo)
                        {
                            MessageBox.Show("Passport has already been add : " + p.m_passport.m_passportNo, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    p.m_booking = m_checkIn;
                    p.m_passengerStatus = PassengerStatus.CheckIn;

                    Trip trip = (Trip)comboBoxDepartureTrip.SelectedValue;
                    int passengerNewNumber = m_bookingService.GetLatestBoardingPassNumber(trip);
                    p.m_boardingPassCode = passengerNewNumber.ToString().PadLeft(3, '0') + trip.m_tripCode + trip.m_departureDate.ToString("ddMMyy");
                    string ticket = generateTicket(p.m_ticketNo, passengerNewNumber.ToString().PadLeft(3, '0'));
                    p.m_ticketNo = ticket;
                    p.m_remark = m_current_user.UserCode;
                    //savepassenger---------
                    m_chekInService.AddPassengerCheckIn(p, m_current_user.TravelAgent);
                    //---------------------=
                    ListViewItem item = listViewPassenger.Items.Add(p.m_boardingPassCode);
                    item.SubItems.Add(p.m_passport.m_passportNo);
                    item.SubItems.Add(p.m_passport.m_name);
                    item.SubItems.Add(p.m_passport.m_gender);
                    item.SubItems.Add(p.m_passport.m_birthDate.ToString("dd-MMM-yyyy"));
                    item.SubItems.Add(p.m_passport.m_nationality);
                    item.SubItems.Add(p.m_passport.m_issueDate.ToString("dd-MMM-yyyy"));
                    item.SubItems.Add(p.m_passport.m_expireDate.ToString("dd-MMM-yyyy"));
                    item.SubItems.Add(p.m_ticketNo);
                    item.SubItems.Add(p.m_passengerStatus.ToString());
                    item.SubItems.Add(p.m_remark);
                    item.Tag = p;
                    calculateBook();
                    lockTripIfPassengerAdded();
                    item.Selected = true;
                }
                else
                {
                    foreach (ListViewItem item in listViewPassenger.Items)
                    {
                        if (item.Tag == null) continue;
                        Passenger psg = (Passenger)item.Tag;
                        if (psg.m_passangerID == p.m_passangerID)
                        {
                            item.SubItems[0].Text = p.m_passport.m_passportNo;
                            item.SubItems[1].Text = p.m_passport.m_name;
                            item.SubItems[2].Text = p.m_passport.m_gender;
                            item.SubItems[3].Text = p.m_passport.m_birthDate.ToString("dd-MMM-yyyy");
                            item.SubItems[4].Text = p.m_passport.m_nationality;
                            item.SubItems[5].Text = p.m_passport.m_issueDate.ToString("dd-MMM-yyyy");
                            item.SubItems[5].Text = p.m_passport.m_expireDate.ToString("dd-MMM-yyyy");
                            item.SubItems[6].Text = p.m_ticketNo;
                            item.SubItems[7].Text = p.m_passengerStatus.ToString();
                            item.SubItems[7].Text = p.m_remark;
                            item.Tag = psg;
                            calculateBook();
                            item.Selected = true;

                        }
                    }
                }
            }

        }

        private void lockTripIfPassengerAdded()
        {
           // comboBoxDepartureTrip.Enabled = listViewPassenger.Items.Count > 0;
        }

        private void calculateBook()
        {
            //if (listViewPassenger.Items.Count > numericUpDownBooked.Value)
            //    numericUpDownBooked.Value = listViewPassenger.Items.Count;
            //labelCount.Text = listViewPassenger.Items.Count.ToString() + "/" + numericUpDownBooked.Value.ToString();
        }

        private void buttonREmove_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem != null)
            {
                if (listViewPassenger.SelectedItem.Tag == null) return;
                Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
                MessageBox.Show(string.Format("Are you sure to delete this passenger : {0}?", p.m_passportNo), "Delete Confirmation", MessageBoxButtons.YesNo,
                MessageBoxIcon.Question, new EventHandler(DeleteConfirmation));
            }
            //lockTripIfPassengerAdded();
        }

        void DeleteConfirmation(object sender, EventArgs e)
        {
            MessageBoxWindow msg = (MessageBoxWindow)sender;
            if (msg.DialogResult == DialogResult.Yes)
            {
                if (listViewPassenger.SelectedItem.Tag == null) return;
                Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
                if (p.m_passengerStatus == PassengerStatus.CheckIn || p.m_passengerStatus == PassengerStatus.UnBoarded)
                {
                    m_chekInService.RemovePassengerCheckIn(p);
                    UpdatePassengerList();
                    //listViewPassenger.Items.RemoveAt(listViewPassenger.SelectedItem.Index);
                    //calculateBook();
                }
                else
                {
                    MessageBox.Show("Status has confirmed, could not delete passenger : " + p.m_passport.m_passportNo, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void listViewPassenger_SelectedIndexChanged(object sender, EventArgs e)
        {
            buttonPrintItiPassenger.Enabled = false;
            buttonBoardingPass.Enabled = false;
            buttonBoardingPass2Way.Enabled = false;
            buttonWildCard.Enabled = false;
            buttonKIMS.Enabled = false;
            buttonViewPassenger.Enabled = false;
            buttonREmove.Enabled = false;
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger pass = (Passenger)listViewPassenger.SelectedItem.Tag;

            //if (m_editmode == EditMode.Create || m_editmode == EditMode.Edit)
            //{
            //    if (listViewPassenger.SelectedItem != null)
            //    {
                    
            //        // && ((Passenger)listViewPassenger.SelectedItem.Tag).m_passengerStatus != PassengerStatus.Confirmed;
            //    }
            //}

            buttonREmove.Enabled = (pass.m_passengerStatus == PassengerStatus.CheckIn || pass.m_passengerStatus == PassengerStatus.UnBoarded) && m_current_user.RoleDetails(this.Name).UpdateFlag;//toolBarButtonSave.Enabled && ;
            buttonPrintItiPassenger.Enabled = (m_checkIn.m_bookingID > 0 && pass.m_passengerStatus == PassengerStatus.CheckIn || pass.m_passengerStatus == PassengerStatus.UnBoarded) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            buttonBoardingPass.Enabled = (m_checkIn.m_bookingID > 0 && pass.m_passengerStatus == PassengerStatus.CheckIn || pass.m_passengerStatus == PassengerStatus.UnBoarded) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            buttonBoardingPass2Way.Enabled = buttonBoardingPass.Enabled;
            buttonWildCard.Enabled = (m_checkIn.m_bookingID > 0 && pass.m_passengerStatus == PassengerStatus.CheckIn || pass.m_passengerStatus == PassengerStatus.UnBoarded) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            buttonKIMS.Enabled = buttonWildCard.Enabled;
            buttonViewPassenger.Enabled = listViewPassenger.SelectedItem != null;
        }

        private void numericUpDownBooked_ValueChanged(object sender, EventArgs e)
        {
            calculateBook();
        }

        private void comboBoxTravelAgent_SelectedIndexChanged(object sender, EventArgs e)
        {
            //timerUpdateBalance_Tick(sender, e);
        }

        private void buttonPrintItiPassenger_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
            if (p.m_passangerID == 0)
            {
                MessageBox.Show("Please save checkin before print the itinerary pass", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            PrintItineraryPassengerForm ppit = new PrintItineraryPassengerForm(p.m_passangerID, m_current_user);
            ppit.ShowDialog();
        }

        private void comboBoxDepartureTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxDepartureTime.SelectedValue == null) return;
            TripTime tt = (TripTime)comboBoxDepartureTime.SelectedValue;
            comboBoxDepartureTrip.Text = tt.m_tripCode;
        }

        private void dateTimePickerReturn_ValueChanged(object sender, EventArgs e)
        {
            //comboBoxReturnTrip.DataSource = null;
            //if (comboBoxReturnSeaPort.SelectedValue == null) return;
            //SeaPort port = (SeaPort)comboBoxReturnSeaPort.SelectedValue;
            //comboBoxReturnTrip.DataSource = m_tripService.LoadAllTripByDateAndSeaPort(dateTimePickerReturnDate.Value, port.m_seaPortID);
            //IList datasource = m_tripService.LoadAllTripByDateAndSeaPort(dateTimePickerReturnDate.Value, port.m_seaPortID);
            //comboBoxReturnTime.DataSource = GetTimeList(datasource);
        }

        private void comboBoxReturnTripTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (comboBoxReturnTime.SelectedValue == null) return;
            //TripTime tt = (TripTime)comboBoxReturnTime.SelectedValue;
            //comboBoxReturnTrip.Text = tt.m_tripCode;
        }

        private void buttonViewPassenger_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem != null)
            {
                if (listViewPassenger.SelectedItem.Tag == null) return;
                Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
                if (!(p.m_passengerStatus == PassengerStatus.Boarding))
                //if (toolBarButtonSave.Enabled)
                {
                    PassengerForm frm = new PassengerForm(this.Name, p, p.m_passport, m_current_user, m_mainForm, this, EditMode.Edit);
                    frm.ShowDialog();
                }
                else
                {
                    PassengerForm frm = new PassengerForm(this.Name, p, p.m_passport, m_current_user, m_mainForm, this, EditMode.Load);
                    frm.ShowDialog();
                }
            }
        }

        private void comboBoxDepartureTrip_SelectedIndexChanged(object sender, EventArgs e)
        {
            buttonAddPassenger.Enabled = comboBoxDepartureTrip.SelectedValue != null;
        }

        private void buttonBoardingPass_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
            if (p.m_passangerID == 0)
            {
                MessageBox.Show("Please save checkin before print the boarding pass", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (p.m_passengerStatus ==  PassengerStatus.Booking)
            {
                MessageBox.Show("Please update status to checkin before print the boarding pass", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (m_current_user.DirectPrintBP)
            {
                m_reportRequest.AddReportRequest(this.Context.HttpContext.Request.ServerVariables["remote_addr"], "BP", p.m_passangerID, m_current_user.MACAddress,
                    m_current_user.PrinterNameBP, m_current_user.PrinterNameWC, m_current_user.PrinterNameKIMS);
            }
            else
            {
                PrintBoardingPassForm ppit = new PrintBoardingPassForm(p.m_passangerID,m_current_user, true);
                ppit.ShowDialog();
            }
        }

        private void buttonWildCard_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
            if (p.m_passangerID == 0)
            {
                MessageBox.Show("Please save checkin before print the wildcard", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (p.m_passengerStatus == PassengerStatus.Booking)
            {
                MessageBox.Show("Please update status to checkin before print the wildcard", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (m_current_user.DirectPrintWC)
            {
                m_reportRequest.AddReportRequest(this.Context.HttpContext.Request.ServerVariables["remote_addr"], "WC", p.m_passangerID, m_current_user.MACAddress,
                    m_current_user.PrinterNameBP, m_current_user.PrinterNameWC, m_current_user.PrinterNameKIMS);
            }
            else
            {
                PrintWildCardForm ppit = new PrintWildCardForm(p.m_passangerID, m_current_user);
                ppit.ShowDialog();
            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            if(buttonAddPassenger.Enabled)
                buttonAddPassenger_Click(sender, e);
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            if (buttonREmove.Enabled)
                buttonREmove_Click(sender, e);
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            if (buttonViewPassenger.Enabled)
                buttonViewPassenger_Click(sender, e);
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            if (buttonPrintItiPassenger.Enabled)
                buttonPrintItiPassenger_Click(sender, e);
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            if (buttonWildCard.Enabled)
                buttonWildCard_Click(sender, e);
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            if (buttonBoardingPass.Enabled)
                buttonBoardingPass_Click(sender, e);
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            toolBarButtonRefresh_Click(sender, e);
        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            //boarding pass 2 way
            if (buttonBoardingPass2Way.Enabled)
                buttonBoardingPass2Way_Click(sender, e);
        }

        private void buttonBoardingPass2Way_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
            if (p.m_passangerID == 0)
            {
                MessageBox.Show("Please save checkin before print the boarding pass", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (p.m_passengerStatus == PassengerStatus.Booking)
            {
                MessageBox.Show("Please update status to checkin before print the boarding pass", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (m_current_user.DirectPrintBP)
            {
                m_reportRequest.AddReportRequest(this.Context.HttpContext.Request.ServerVariables["remote_addr"], "BP2", p.m_passangerID, m_current_user.MACAddress,
                    m_current_user.PrinterNameBP, m_current_user.PrinterNameWC, m_current_user.PrinterNameKIMS);
            }
            else
            {
                PrintBoardingPassForm ppit = new PrintBoardingPassForm(p.m_passangerID, m_current_user, false);
                ppit.ShowDialog();
            }
        }

        private void buttonKIMS_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem == null) return;
            if (listViewPassenger.SelectedItem.Tag == null) return;
            Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
            if (p.m_passangerID == 0)
            {
                MessageBox.Show("Please save checkin before print the wildcard", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (p.m_passengerStatus == PassengerStatus.Booking)
            {
                MessageBox.Show("Please update status to checkin before print the wildcard", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (m_current_user.DirectPrintKIMS)
            {
                m_reportRequest.AddReportRequest(this.Context.HttpContext.Request.ServerVariables["remote_addr"], "KIMS", p.m_passangerID, m_current_user.MACAddress,
                    m_current_user.PrinterNameBP, m_current_user.PrinterNameWC, m_current_user.PrinterNameKIMS);
            }
            else
            {
                PrintKIMSCardForm ppit = new PrintKIMSCardForm(p.m_passangerID, m_current_user);
                ppit.ShowDialog();
            }
        }

        private void menuItem11_Click(object sender, EventArgs e)
        {
            if (buttonKIMS.Enabled)
                buttonKIMS_Click(sender, e);
        }

        private void textBoxSearchPassenger_EnterKeyDown(object objSender, KeyEventArgs objArgs)
        {
            labelResult.Text = "";
            listViewPassenger.SelectedItems.Clear();
            if (textBoxSearchPassenger.Text.Trim() == "") return;
            foreach (ListViewItem itm in listViewPassenger.Items)
            {
                Passenger px = (Passenger)itm.Tag;
                itm.Selected = px.m_passportNo.ToLower().Contains(textBoxSearchPassenger.Text.ToLower().Trim());
                if (!itm.Selected)
                    itm.Selected = px.m_name.ToLower().Contains(textBoxSearchPassenger.Text.ToLower().Trim());
            }
            if (listViewPassenger.SelectedItems.Count == 0)
                labelResult.Text = "No matches found for '" + textBoxSearchPassenger.Text.Trim() + "'";
            else
                labelResult.Text = "Matches found : " + listViewPassenger.SelectedItems.Count.ToString() + " item(s)";
        }
    }
}